package com.example.tb.utils;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;

import java.io.InputStream;
import java.util.List;

public class DataUtils {

    public static class HuToolExcelUtil {
        /**
         * 获取导入数据
         * @param bookStream 文件流
         * @param clazz 转换类
         * @param property 属性名
         * @param <T> 返回值
         * @return
         */
        public static <T> List<T> loadDown(InputStream bookStream, Class<T> clazz, String ...property) {
            ExcelReader reader = ExcelUtil.getReader(bookStream);
            Sheet sheet = reader.getSheet();
            Row sheetTitleRow = sheet.getRow(sheet.getFirstRowNum());
            int physicalNumberOfCells = sheetTitleRow.getPhysicalNumberOfCells();
            //获取表头数量
            int cellCount = 0;
            for (int i = 0; i < physicalNumberOfCells; i++) {
                Cell cell = sheetTitleRow.getCell(i);
                String stringCellValue = cell.getStringCellValue();
                if (StringUtils.isNotBlank(stringCellValue)) {
                    cellCount += 1;
                }
            }
            if (property.length != cellCount) {
                throw new RuntimeException("指定属性数量与文件表头数不一致");
            }
            //替换标题为属性名
            for (int i = 0; i < cellCount; i++) {
                Cell cell = reader.getCell(i, 0);
                cell.setCellValue(property[i]);
            }
            return reader.readAll(clazz);
        }

    }
}